package cn.com.infcn.spider.io.output.impl;

import java.util.concurrent.ConcurrentLinkedQueue;

import com.alibaba.fastjson.JSONObject;

import cn.com.infcn.spider.domain.Doc;
import cn.com.infcn.spider.io.output.Output;
import cn.com.infcn.spider.util.BasicDao;

/**
 * jdbc输出
 * 
 * @author Ansj
 *
 */
public class jdbcOutput implements Output {

	private ConcurrentLinkedQueue<JSONObject> queue = null;

	private BasicDao basicDao = null;

	private String tableName = null;

	private int batchSize = 0;

	public jdbcOutput(JSONObject job, String jobName) {
		basicDao = new BasicDao(job.getString("jdbcUrl"), job.getString("username"), job.getString("password"));
		tableName = job.getString("tableName");
		batchSize = job.getIntValue("batchSize");
		if (tableName == null) {
			throw new RuntimeException("not set tableName! in " + job.toJSONString().replace("\n", " "));
		}
		basicDao.getDao().query(tableName, null, this.basicDao.getDao().createPager(1, 1)); // 查询一条记录判断表是否好着呢
	}

	@Override
	public void save(Doc doc) {

		if (queue == null) {
			basicDao.save(tableName, doc.getResult());
		} else {
			queue.add(doc.getResult());
			if (queue.size() >= batchSize) {
				flush();
			}
		}

	}

	@Override
	public synchronized void flush() {
		batchSave();
	}

	public synchronized void batchSave() {
		JSONObject job = null;
		if (queue != null){
			while ((job = queue.poll()) != null) {
				try {
					basicDao.save(tableName, job);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

	@Override
	public void shutdown() {
		flush();
	}

}
